﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Ebada.Platform.Model;
using Ebada.UI.Base;
using Ebada.Client;
using Ebada.Core;
using Ebada.Client.Platform;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Ebada.Modules.Vehicle
{
    /// <summary>
    /// 车辆登记编辑
    /// </summary>
    public partial class frmVehiclesEdit : FormBase, IPopupFormEdit {
        SortableSearchableBindingList<mOrg> m_OrgID = new SortableSearchableBindingList<mOrg>();
        SortableSearchableBindingList<Empolyees> m_Employ= new SortableSearchableBindingList<Empolyees>();

        public frmVehiclesEdit()
        {
            InitializeComponent();
        }
        private void frmVehiclesEdit_Load(object sender, EventArgs e)
        {

            Add_FromDIC();

        }
        void dataBind() 
        {

            this.txtVehicleCode.DataBindings.Add("EditValue", rowData, "VehicleCode");
            this.txtVehicleNumber.DataBindings.Add("EditValue", rowData, "VehicleNumber");
            this.cobVehicleType.DataBindings.Add("EditValue", rowData, "VehicleType");
            this.txtOldVehicleNumber.DataBindings.Add("EditValue", rowData, "OldVehicleNumber");
            this.cobUsageType.DataBindings.Add("EditValue", rowData, "UsageType");
            this.txtVehicleModel.DataBindings.Add("EditValue", rowData, "VehicleModel");
            this.cobTonnage.DataBindings.Add("EditValue", rowData, "Tonnage");
            this.daeRegDate.DataBindings.Add("EditValue", rowData, "RegDate");
            this.cobColor.DataBindings.Add("EditValue", rowData, "Color");
            this.cobBrand.DataBindings.Add("EditValue", rowData, "Brand");
            this.txtPersonnelAllocationNum.DataBindings.Add("EditValue", rowData, "PersonnelAllocationNum");
            this.luOrgCode.DataBindings.Add("EditValue", rowData, "OrgCode");

            this.luUsingOrgCode.DataBindings.Add("EditValue", rowData, "UsingOrgCode");

            this.luEmployeeNo.DataBindings.Add("EditValue", rowData,"EmployeeNo");

            this.txtVINNum.DataBindings.Add("EditValue", rowData, "VINNum");
            this.txtEngineNum.DataBindings.Add("EditValue", rowData, "EngineNum");
            this.txtPurchaseTax.DataBindings.Add("EditValue", rowData, "PurchaseTax");
            this.daePurchaseDate.DataBindings.Add("EditValue", rowData, "PurchaseDate");
            this.txtAcquisitionPrice.DataBindings.Add("EditValue", rowData, "AcquisitionPrice");
            this.txtPurchasePrice.DataBindings.Add("EditValue", rowData, "PurchasePrice");
            this.txtPurchaseTaxNum.DataBindings.Add("EditValue", rowData, "PurchaseTaxNum");
            this.txtInsuranceOrgName.DataBindings.Add("EditValue", rowData, "InsuranceOrgName");
            this.txtInsurancePrice.DataBindings.Add("EditValue", rowData, "InsurancePrice");
            this.daeInsuranceStartDate.DataBindings.Add("EditValue", rowData, "InsuranceStartDate");
            this.daeInsuranceEndDate.DataBindings.Add("EditValue", rowData, "InsuranceEndDate");
            this.meRemark.DataBindings.Add("EditValue", rowData, "Remark");
            this.picVehicleImage.DataBindings.Add("EditValue", rowData, "VehicleImage");
            this.cobVehicleState.DataBindings.Add("EditValue", rowData, "VehicleState");
        }
      
        Vehicle_Common vc = new Vehicle_Common();

        private void Add_FromDIC()
        {
            vc.Add_DIC("UsageType", cobUsageType);
            vc.Add_DIC("Tonnage", cobTonnage);
            vc.Add_DIC("Color", cobColor);
            vc.Add_DIC("Brand", cobBrand);
            vc.Add_DIC("VehicleState", cobVehicleState);
            vc.Add_DIC("VehicleType", cobVehicleType);
        }
        /// <summary>
        /// 维护下拉列表 从数据库中取出所有不同的加入
        /// </summary>
        private void Add_ComboxAll()
        {

            cobUsageType.Properties.Items.Clear();

            cobTonnage.Properties.Items.Clear();

            cobColor.Properties.Items.Clear();

            cobBrand.Properties.Items.Clear();
            cobVehicleState.Properties.Items.Clear();
            //用途UsageType
            //吨位人数Tonnage
            //颜色Color
            //车辆品牌Brand
            Hashtable UsageType = new Hashtable();
            Hashtable Tonnage = new Hashtable();
            Hashtable Color = new Hashtable();
            Hashtable Brand = new Hashtable();
            Hashtable stateh = new Hashtable();
            IList<Vehicles> vehi_list = MainHelper.PlatformSqlMap.GetList<Vehicles>("");
            for (int i = 0; i < vehi_list.Count; i++)
            {
                string Usa = vehi_list[i].UsageType;
                string Ton = Math.Round(vehi_list[i].Tonnage, 0).ToString();
                string Col = vehi_list[i].Color;
                string Bra = vehi_list[i].Brand;
                string state = vehi_list[i].VehicleState;
                if (!UsageType.ContainsKey(Usa) && Usa != "")
                {
                    UsageType.Add(Usa, Usa);
                }
                if (!Tonnage.ContainsKey(Ton) && Ton != "")
                {
                    Tonnage.Add(Ton, Ton);
                }
                if (!Color.ContainsKey(Col) && Col != "")
                {
                    Color.Add(Col, Col);
                }
                if (!Brand.ContainsKey(Bra) && Bra != "")
                {
                    Brand.Add(Bra, Bra);
                }
                if (!stateh.ContainsKey(state) && state != "")
                {
                    stateh.Add(state, state);
                }
            }
            foreach (string key in UsageType.Keys)
            {
                cobUsageType.Properties.Items.Add(key);
            }
            foreach (string key in Tonnage.Keys)
            {
                cobTonnage.Properties.Items.Add(key);
            }
            foreach (string key in Color.Keys)
            {
                cobColor.Properties.Items.Add(key);
            }
            foreach (string key in Brand.Keys)
            {
                cobBrand.Properties.Items.Add(key);
            }
            foreach (string key in stateh.Keys)
            {
                cobVehicleState.Properties.Items.Add(key);
            }

        }
        #region IPopupFormEdit Members
        private Vehicles rowData = null;

        public object RowData {
            get {
                return rowData;
            }
            set {
                if (value == null) return;
                if (rowData == null) {
                    this.rowData = value as Vehicles;
                    dataBind();
                    InitComboBoxData();
                } else {
                    ConvertHelper.CopyTo<Vehicles>(value as Vehicles, rowData);
                    //picVehicleImage.Image = null;
                    //if (rowData.VehicleImage != null && rowData.VehicleImage.Length != 0)
                    //{
                    //    picVehicleImage.Image = ReadImage(rowData.VehicleImage);
                    //    picVehicleImage.Refresh();
                    //}
                    //else
                    //{
                    //    picVehicleImage.Image = null;
                    //}
                }
            }
        }

        #endregion

        private void InitComboBoxData() 
        {
            IList<mOrg> morg_list = MainHelper.PlatformSqlMap.GetList<mOrg>("");
            IList<Empolyees> empl_list = MainHelper.PlatformSqlMap.GetList<Empolyees>("");
            this.SetComboBoxData(this.luOrgCode, "cnName", "OrgCode", "请选择", "单位名称", morg_list);
            this.SetComboBoxData(this.luUsingOrgCode, "cnName", "OrgCode", "请选择", "单位名称", morg_list);
            this.SetComboBoxData2(this.luEmployeeNo, "Empolyee_Name", "Empolyee_ID", "请选择", "人员名称", empl_list);
          
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="comboBox"></param>
        /// <param name="displayMember"></param>
        /// <param name="valueMember"></param>
        /// <param name="nullTest"></param>
        /// <param name="cnStr"></param>
        /// <param name="post"></param>
       //单位选择器
        public void SetComboBoxData(DevExpress.XtraEditors.LookUpEdit comboBox, string displayMember, string valueMember, string nullTest, string cnStr, IList<mOrg> post)
        {
            comboBox.Properties.Columns.Clear();
            comboBox.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            comboBox.Properties.DataSource = post;
            comboBox.Properties.DisplayMember = displayMember;
            comboBox.Properties.ValueMember = valueMember;
            comboBox.Properties.NullText = nullTest;
            comboBox.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
            new DevExpress.XtraEditors.Controls.LookUpColumnInfo(valueMember, "ID", 20, DevExpress.Utils.FormatType.None, "", false, DevExpress.Utils.HorzAlignment.Default),
            new DevExpress.XtraEditors.Controls.LookUpColumnInfo(displayMember, cnStr)});
        }
        //人员选择器
        public void SetComboBoxData2(DevExpress.XtraEditors.LookUpEdit comboBox, string displayMember, string valueMember, string nullTest, string cnStr, IList<Empolyees> post)
        {
            comboBox.Properties.Columns.Clear();
            comboBox.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            comboBox.Properties.DataSource = post;
            comboBox.Properties.DisplayMember = displayMember;
            comboBox.Properties.ValueMember = valueMember;
            comboBox.Properties.NullText = nullTest;
            comboBox.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
            new DevExpress.XtraEditors.Controls.LookUpColumnInfo(valueMember, "ID", 20, DevExpress.Utils.FormatType.None, "", false, DevExpress.Utils.HorzAlignment.Default),
            new DevExpress.XtraEditors.Controls.LookUpColumnInfo(displayMember, cnStr)});
        }
     
      

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtVehicleCode.Text.Length == 0)
            {
                MessageBox.Show("序号不能为空！");
                txtVehicleCode.Focus();
                return;
            }
            if (txtVehicleNumber.Text.Length == 0)
            {
                MessageBox.Show("车牌号码不能为空！");
                txtVehicleNumber.Focus();
                return;
            }

            if (cobVehicleType.Text.Length == 0)
            {
                MessageBox.Show("车辆类型不能为空！");
                cobVehicleType.Focus();
                return;
            }

             if (luOrgCode.Text.Length == 0)
            {
                MessageBox.Show("车属单位不能为空！");
                luOrgCode.Focus();
                return;
            }
             IList<Vehicles> objlist = MainHelper.GetSqlMap<Vehicles>().GetListByWhere<Vehicles>(" where VehicleNumber='" + txtVehicleNumber.Text + "'");
             if (objlist.Count > 0)
             {
                 if (rowData.VehicleID != objlist[0].VehicleID)
                 {
                     MessageBox.Show("此车牌已经存在。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                     return;
                 }
             }
            if (picVehicleImage.Image == null)
            {
                rowData.VehicleImage = new byte[0];
            }
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        //所属单位选择
        private void luOrgCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1)
            {

                frmOrgSelector2 frm = new frmOrgSelector2();
                frm.IntionDataAll();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    luOrgCode.EditValue = frm.SelectObj.OrgCode;
                    rowData.OrgName = frm.SelectObj.cnName;
                    
                }

            }
        }
        private void luOrgCode_EditValueChanged(object sender, EventArgs e)
        {
            rowData.OrgName = luOrgCode.Text;
        }
        //使用单位选择
        private void luUsingOrgCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1)
            {
                frmOrgSelector2 frm = new frmOrgSelector2();
                frm.IntionDataAll();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    luUsingOrgCode.EditValue= frm.SelectObj.OrgCode;
                    rowData.UsingOrgName = frm.SelectObj.cnName;
                    
                }
            }
        }
        private void luUsingOrgCode_EditValueChanged(object sender, EventArgs e)
        {
            rowData.UsingOrgName = luUsingOrgCode.Text;
        }
        //车主驾驶人中选择
        private void luEmployeeNo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1)
            {
                Ebada.Client.Platform.Selector.frmEmpSelectorByOrgInfo frm = new Ebada.Client.Platform.Selector.frmEmpSelectorByOrgInfo();
                frm.InitionData("", false, false);
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    luEmployeeNo.EditValue = frm.CurrentEmp.Empolyee_ID;
                    rowData.EmployeeName = frm.CurrentEmp.Empolyee_Name;
                }
            }
        }
        private void luEmployeeNo_EditValueChanged(object sender, EventArgs e)
        {
            rowData.EmployeeName = luEmployeeNo.Text;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            //string filepath = "";
            //openFileDialog1.Filter = "图片文件|*.jpeg;*.jpg;*.gif;*.png";
            //if (openFileDialog1.ShowDialog() == DialogResult.OK)
            //{
            //    filepath = openFileDialog1.FileName;
            //      FileStream fs = new FileStream(filepath, FileMode.Open,FileAccess.Read);
            //      Byte[] btye2 = new byte[fs.Length];
            //       fs.Read(btye2 , 0, Convert.ToInt32(fs.Length));                 
            //       picVehicleImage.Image = Image.FromStream(fs);
            //       rowData.VehicleImage = ConvertImage(picVehicleImage.Image);
                  
              
               
            //}
            string filepath = "";
            openFileDialog1.Filter = "图片文件|*.jpeg;*.jpg;*.bmp;*.gif;*.png";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filepath = openFileDialog1.FileName;
                FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
                Byte[] btye2 = new byte[fs.Length];
                fs.Read(btye2, 0, Convert.ToInt32(fs.Length));
                picVehicleImage.Image = Image.FromStream(fs);
                rowData.VehicleImage = btye2;
            }
        }

        public byte[] ConvertImage(Image image)
        {
            FileStream fs = new FileStream("imagetemp", FileMode.Create, FileAccess.Write, FileShare.None);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, (object)image);
            fs.Close();
            fs = new FileStream("imagetemp", FileMode.Open, FileAccess.Read, FileShare.None);
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, (int)fs.Length);
            fs.Close();
            return bytes;
        }


        public Image ReadImage(byte[] bytes)
        {
            FileStream fs = new FileStream("imagetemp1", FileMode.Create, FileAccess.Write, FileShare.None);
            foreach (byte a in bytes)
            {
                fs.WriteByte(a);
            }
            fs.Close();
            fs = new FileStream("imagetemp1", FileMode.Open, FileAccess.Read, FileShare.None);
            BinaryFormatter bf = new BinaryFormatter();
            object obj = bf.Deserialize(fs);
            fs.Close();
            return (Image)obj;
        }

       

      

      



      
    }
}